#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : Chestnut
# @time    : 2025/6/5 10:10
# @function: What can I do.
# @version : V1
import math
import os
import numpy as np

from tqdm import tqdm
from tkinter import filedialog
import openpyxl


class Converter:
    def __init__(self,new_filename):
        '''
        读取xlsx文件，需要指定源文件位置和存储文件的位置
        :param origin_filename: 原始数据存放绝对路径
        :param new_filename: 新文件绝对路径（文件夹）
        '''
        self.o_name = filedialog.askopenfilename()
        self.fr_name = os.path.join(new_filename, f"{os.path.basename(self.o_name)}_fftr.xlsx")
        self.fi_name = os.path.join(new_filename, f"{os.path.basename(self.o_name)}_ffti.xlsx")
        self.i_name = os.path.join(new_filename,f"{os.path.basename(self.o_name)}_info.xlsx")
        self.wb1 = openpyxl.load_workbook(self.o_name)
        self.ws1 = self.wb1.active
        try:
            self.wb2 = openpyxl.load_workbook(self.fr_name)
            self.ws2 = self.wb2.active
        except:
            self.wb2 = openpyxl.Workbook()
            self.ws2 = self.wb2.active
        try:
            self.wb3 = openpyxl.load_workbook(self.i_name)
            self.ws3 = self.wb3.active
        except:
            self.wb3 = openpyxl.Workbook()
            self.ws3 = self.wb3.active
        self.data = list()
        self.channel_name = "None"
        self.column_index = 0
        self.info_list = [["channel_name"], ["mean"], ["vpp97"]]

    def main(self):
        '''
        主入口
        :return:
        '''
        for column_index in tqdm(range(1, self.ws1.max_column + 1)):
            self.channel_name = self.ws1.cell(row=1, column=column_index).value
            self.column_index = column_index
            self.info_list[0].append(self.channel_name)
            for row_index in range(2, self.ws1.max_row):
                self.data.append(self.ws1.cell(row_index, column_index).value)
            self.get_mean()
            self.get_vpp97()
            self.data = []
            # print(self.info_list)


    def save_as_excel(self):
        for i, c_n in enumerate(self.info_list[0]):
            self.ws3.cell(row=1, column=i + 1).value = c_n
        if len(self.info_list[1]) != 0:
            for i, _m in enumerate(self.info_list[1]):
                self.ws3.cell(row=2, column=i + 1).value = _m
        if len(self.info_list[2]) != 0:
            for i, _v in enumerate(self.info_list[2]):
                self.ws3.cell(row=3, column=i + 1).value = _v
        self.wb3.save(self.i_name)
        # for i, c_n in enumerate(self.info_list[3]):
        #     self.ws2.cell(row=1, column=i + 1).value = c_n

    def get_mean(self):
        mean = sum(self.data) / len(self.data)
        mean = mean * 0.21
        # print(f"{self.channel_name}: {mean}(mean)")
        self.info_list[1].append(mean)

    def get_vpp97(self):
        sorted_list = sorted(self.data)  # 由低到高
        low_index = math.floor(len(sorted_list) * 0.015)
        high_index = math.floor(len(sorted_list) * 0.985)
        vpp97 = sorted_list[high_index] - sorted_list[low_index]
        vpp97 = vpp97 * 0.21
        # print(f"{self.channel_name}: {vpp97}(vpp97)")
        self.info_list[2].append(vpp97)

    def _fft(self):
        fft_data = np.array(self.data)
        fft_result = np.fft.fft(fft_data)
        self.ws2.append(['原始数据', 'FFT实部', 'FFT虚部'])

        # 写入数据

        for i in range(len(fft_data)):
            self.ws2.append([fft_data[i], fft_result[i].real, fft_result[i].imag])



if __name__ == '__main__':
    new_path = r"E:\20250526 漫湾转轮动应力&稳定性试验\20250429 大轴应力必创数据\txt绝对时间格式\XLSX文件"
    converter = Converter(new_path)
    converter.main()
    converter.save_as_excel()
